package com.wave.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.wave.entity.Auth;
import com.wave.entity.User;
import com.wave.entity.WeChatConfig;
import com.wave.service.UserService;
import com.wave.service.AuthService;
import com.wave.utils.PageUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

// 前后端分离注释
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private WeChatConfig weChatConfig;
    @Autowired
    private AuthService authService;

    @PostMapping("wxLogin")
    public JSONObject wxLogin(@RequestBody JSONObject requestJson){
        String code = requestJson.getString("code");
        String userName = requestJson.getString("userName");
        System.out.println("从前端获得用户名："+userName+" | code："+code);
        //用微信code 访问登录凭证校验接口 用Map方式拼接带参的GET访问请求链接
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code";
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("appid", weChatConfig.getAppid());
        requestMap.put("secret", weChatConfig.getSecret());
        requestMap.put("code", code);
        //用springframework架设服务器RestTemplate来进行Http访问 需要SpringBoot与SpringCloud版本兼容
        //Spring Boot高版本(1.4+) RestTemplate需要Config文件 添加创建restTemplate对象方法
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, requestMap);
        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        String openId = jsonObject.getString("openid");
        String session_key = jsonObject.getString("session_key");
        User user = new User();
        if (userService.selectAccount(openId) == 0){
            System.out.println("用户不存在，自动注册");

            user.setAccount(openId);
            user.setUserName(userName);
            user.setPassword(session_key);
            user.setType(0);
            userService.create(user);
        }else {
            System.out.println("用户账号"+openId);
            String auth = userService.selectAuth(openId);
            if(auth != null && !auth.equals("")){
                //System.out.println("认证用户");
                user = userService.queryDetail(openId);
            }else {
                //System.out.println("游客");
                user = userService.userDetail(openId);
            }
        }
        //System.out.println(user.toString());
        JSONObject respond = new JSONObject();
        respond.put("account", user.getAccount());
        respond.put("userName", user.getUserName());
        respond.put("userType", user.getType());
        respond.put("a_id", user.getAId());
        respond.put("target", user.getaTarget());
        return respond;
    }

    @PostMapping("adminLogin")
    public JSONObject adminLogin(@RequestBody JSONObject requestJson){
        JSONObject respond = new JSONObject();
        String select = requestJson.getString("select");
        String account = requestJson.getString("account");
        String password = requestJson.getString("password");
        if (StrUtil.isBlank(account) || StrUtil.isBlank(password) || StrUtil.isBlank(select)){
            respond.put("tips", "账号或密码不能为空！");
            respond.put("result", false);
            return respond;
        }
        return userService.adminLogin(select, account, password);
    }

    @GetMapping("list")
    public JSONObject getUserList(@RequestParam int pageNum, @RequestParam int pageSize,
                                  @RequestParam String userName, @RequestParam String aid) {
        return userService.getUserList(pageNum, pageSize, userName, aid);
    }

    @PostMapping("alter")
    public int alterUser(@RequestBody JSONObject requestJson){
        User user = new User();
        user.setType(requestJson.getInteger("type"));
        user.setUserName(requestJson.getString("userName"));
        user.setPassword(requestJson.getString("password"));
        user.setAId(requestJson.getString("aid"));
        user.setPhone(requestJson.getString("phone"));
        user.setAccount(requestJson.getString("account"));
        return userService.update(user);
    }

    @PostMapping("alterPassword")
    public boolean alterPassword(@RequestBody JSONObject requestJson){
        String account = requestJson.getString("account");
        String newPassword = requestJson.getString("newPassword");
        String oldPassword = requestJson.getString("oldPassword");
        return userService.alterPassword(account, newPassword, oldPassword);
    }

    @PostMapping("bindAuth")
    public int bindAuthByPhone(@RequestBody JSONObject requestJson){
        String account = requestJson.getString("userAccount");
        String aId = requestJson.getString("aid");
        String phone = requestJson.getString("phone");
        //System.out.println("用户"+account+"身份号"+aId+"手机号"+phone);
        if(phone.equals(userService.getPhone(aId)) ) {
            System.out.println("手机号匹配");
            userService.bindAuth(account, aId, phone);
            return 1;
        }else {
            return 0;
        }
    }

    @PostMapping("excel")
    public List<Auth> excel(@RequestParam(value = "file") MultipartFile uploadFile) throws IOException {
        // 定义一个数据格式化对象
        //XSSFWorkbook wb = null;
        Workbook workbook;
        InputStream inputStream;
        //File file = null;

        try {
            //excel测试本地路径
            //file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/test.xlsx");
            //inputStream = new FileInputStream(file);
            inputStream = uploadFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException("文件读取异常");
        }
        File file  = new File("D:\\springboot\\123");
        file.mkdir();
        String pathName = "D:\\springboot\\123\\";//存储文件的地址
        String pname = uploadFile.getOriginalFilename();//获取文件名（包括后缀）
        pathName += pname;
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(pathName);
            fos.write(uploadFile.getBytes()); // 写入文件
            System.out.println("文件上传成功");
        } catch (Exception e) {
            e.printStackTrace();
        }


        // 根据excel文件版本获取工作簿
        if (Objects.requireNonNull(uploadFile.getOriginalFilename()).endsWith(".xls")) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (Objects.requireNonNull(uploadFile.getOriginalFilename()).endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(inputStream);
        } else {
            throw new RuntimeException("非excel文件");
        }
//        try {
//            //读取excel模板
//            wb = new XSSFWorkbook(inputStream);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        //获取sheet表格，及读取单元格内容
        Sheet sheet;
        List<Auth> authList = new ArrayList<>();
        try{
            // 得到一个工作表
            sheet = workbook.getSheetAt(0);

            // 获取行总数
            int rows = sheet.getLastRowNum() + 1;

            for (int i = 1; i < rows; i++) {
                System.out.println(i);
                Row row = sheet.getRow(i);
                Cell cell = row.getCell(0);
                // 若单元格为空 则创建一个空单元格 才能判断是否为空
                if(cell == null ){
                    cell = row.createCell(0);
                }
                // 判断单元格是否为空
                if (CellType.BLANK != cell.getCellType()) {
                    Auth auth = new Auth();
                    String department;
                    String quarter;
                    //先将获取的单元格设置为String类型，下面使用getStringCellValue获取单元格内容
                    cell.setCellType(CellType.STRING);// 学号
                    auth.setaId(cell.getStringCellValue());

                    row.getCell(1).setCellType(CellType.STRING);// 姓名
                    auth.setaName(row.getCell(1).getStringCellValue());

                    row.getCell(2).setCellType(CellType.STRING);// 系部
                    department = row.getCell(2).getStringCellValue();
                    auth.setaDepartments(department);

                    row.getCell(3).setCellType(CellType.STRING);// 专业
                    auth.setaSpecialities(row.getCell(3).getStringCellValue());

                    row.getCell(4).setCellType(CellType.STRING);// 宿舍
                    quarter = row.getCell(4).getStringCellValue();
                    auth.setaQuarter(quarter);

                    row.getCell(5).setCellType(CellType.STRING);// 手机
                    auth.setaPhone(row.getCell(5).getStringCellValue());

                    String target = ""; //类型标识
                    target = target.concat(authService.getDepartmentId(department));
                    target = target.concat(authService.getQuarterId(quarter));
                    auth.setaTarget(target);

                    row.getCell(6).setCellType(CellType.STRING);// 身份
                    String type = row.getCell(6).getStringCellValue();
                    String aIdentity = null;
                    if (type.equals("学生") || type.equals("3")){
                        aIdentity = "3";
                    }else if (type.equals("老师") || type.equals("2")){
                        aIdentity = "2";
                    }
                    auth.setaIdentity(aIdentity);

                    authService.createAuth(auth);   //数据库存入
                    authService.deleteOld();
                    authList.add(auth);
                }
            }
            return authList;
        }
        catch (Exception e){
            e.printStackTrace();
        }

        return (authList);
    }

    @GetMapping("authList")
    public JSONObject getAuthList(@RequestParam int pageNum, @RequestParam int pageSize,
                                  @RequestParam String aName, @RequestParam String aId,
                                  @RequestParam String aDepartments, @RequestParam String aQuarter,
                                  @RequestParam String aIdentity) {
        return authService.getAuthList(pageNum, pageSize, aName, aId, aDepartments, aQuarter, aIdentity);
    }

    @PostMapping("delete")
    public int deleteAuth(@RequestBody JSONObject requestJson)  {
        int id = requestJson.getInteger("id");
        System.out.println("删除认证编号："+id);
        return authService.delete(id);
    }

    @PostMapping("deleteList")
    public boolean deleteAuthList(@RequestBody List<Integer> idList)  {
        try{
            for (int id : idList) {
                System.out.println("删除认证编号："+id);
                authService.delete(id);
            }
            return true;
        }
        catch (Exception e){
            return false;
        }
    }

    @GetMapping("export")
    public void export(HttpServletResponse response) throws Exception {
        // 数据库取数据
        List<Auth> list = authService.list();

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题
        writer.addHeaderAlias("aId", "身份号");
        writer.addHeaderAlias("aName", "姓名");
        writer.addHeaderAlias("aDepartments", "系部");
        writer.addHeaderAlias("aSpecialities", "专业");
        writer.addHeaderAlias("aQuarter", "生活区");
        writer.addHeaderAlias("aPhone", "手机");
        writer.addHeaderAlias("aIdentity", "身份");
        // 写入对象
        writer.write(list, true);

        // 浏览器响应设置
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户绑定身份认证", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

}
